<!-- 添加企业 编辑企业 -->
<script setup lang='ts' name="org-role-add">
import type { FormInstance } from 'element-plus'

import { useDicts } from '@/pages/company-org/hooks/use-dicts'
import { addCompanyOrg, getAllCompanyOrg, getNewCompanyOrgDetail, useGetCatTypeDictInfo } from '@fl/api/iam-api'
import Address from '@fl/components/address.vue'
import { useAesDecrypt } from '@fl/hooks/web/useCrypt'
import { useUserStore } from '@fl/store/modules/user'
import { ElButton, ElCard, ElCol, ElForm, ElFormItem, ElInput, ElMessage, ElOption, ElRow, ElSelect, ElSwitch } from 'element-plus'
import { getCurrentInstance, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useForm } from './hooks/use-form'
import { useRule } from './hooks/use-rule'

const userStore = useUserStore()
const instance = getCurrentInstance()
const { rules } = useRule(instance)

const orgs = ref<any>([])

const { dicts: { EnterpriseRank } } = useDicts()
const { form } = useForm()
const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const detail = ref<any>({})
const cacheData = ref<any>([])
const isEdit = ref(false)
const isNext = ref(true)

const { data: CatType } = useGetCatTypeDictInfo()

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid)
            saveData()
        else
            console.log('error!', fields)
    })
}

async function saveData() {
    const {
        catTypeId,
        enterpriseId,
        enterpriseLevel,
        enterpriseLevelId,
        enterpriseName,
        parentId,
        phonenumber,
        registeredAddress, // 企业注册地
        status,
        unifiedSocialCreditCode,
        userName,
    } = form

    const data: any = {
        catTypeId: catTypeId.sort().join(','),
        enterpriseAccount: 10000, // 固定 10000
        enterpriseId,
        enterpriseLevel,
        enterpriseLevelId,
        enterpriseName,
        parentId,
        phonenumber,
        registeredAddress, // 企业注册地
        status,
        unifiedSocialCreditCode,
        userName,
    }

    // 编辑必传
    if (isEdit.value)
        data.id = form.id

    sendFlow(data)
}

function sendFlow(data: any) {
    console.log('保存', data)
    data.createBy = userStore.getUserInfo?.id
    data.createdName = userStore.getUserInfo?.name
    addCompanyOrg(data).then(async (res: any) => {
        if (res?.code === 200) {
            ElMessage.success('保存成功')
            setTimeout(() => {
                goToList()
            }, 1000)
        }
        else {
            ElMessage({ message: res.msg, type: 'error' })
        }
    })
}

function enterpriseLevelChange(val: any) {
    if (val === '1') {
        form.parentId = form.enterpriseName
        form.enterpriseLevel = '一级企业'
    }
    else {
        form.parentId = ''
        form.enterpriseLevel = '二级企业'
    }
}

function goToList() {
    router.replace('/house-source-center/fair/user-management')
}

function dmChange(value: string, fn?: any) {
    const target = cacheData.value.find((v: any) => v.unifiedSocialCreditCode === value) ?? ''

    if (target) {
        ElMessageBox.confirm(
            '该企业已存在，是否编辑?',
            '提示',
            {
                type: 'warning',
            },
        ).then(() => {
            isEdit.value = true
            detail.value = target

            console.log('当前企业', target)
            Object.assign(form, {
                ...target,
                catTypeId: [],
                phonenumber: useAesDecrypt(target.phonenumber),
            })

            fn()
        }).catch(() => {
            isEdit.value = false
            detail.value = {
                ...form,
            }
            isNext.value = false
        })
    }
    else {
        fn()
    }
}

function init(val: any) {
    const id = val.query?.id
    isEdit.value = !!id
    console.log('init', id, isEdit)

    // 所有公司列表
    getAllCompanyOrg({ page: 1, size: 9999 }).then((res: any) => {
        const data = res?.data ?? []
        data.forEach((v: any) => {
            if (v.enterpriseId) {
                orgs.value.push({
                    ...v,
                    label: v.enterpriseName,
                    value: v.enterpriseId,
                })
            }
        })
        // console.log('orgs', orgs.value)
    })
    if (!isEdit.value)
        return
    // 详情
    getNewCompanyOrgDetail(id).then((res: any) => {
        if (res.code === 200) {
            Object.assign(form, {
                ...res.data,
                catTypeId: res.data.catTypeId ? res.data.catTypeId.split(',') : [],
            })
            // console.log('企业详情form', form)
        }
    })
}

watch(route, (val: any) => {
    init(val)
}, {
    deep: true,
    immediate: true,
})

defineExpose({
    dmChange,
    isEdit,
    isNext,
})

// 根据信用代码判断是否存在企业 91420102MABUBY349L
function creditCodeChange(val) {
    if (val.length === 18) {
        const target = orgs.value.find((v: any) => v.unifiedSocialCreditCode === val)
        if (!target)
            return
        ElMessageBox.confirm(
            '该企业已存在，是否编辑?',
            '提示',
            {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning',
            },
        )
            .then(() => {
                isEdit.value = true
                // 加上房交会业务：8
                const catTypeId = target.catTypeId ? Array.from(new Set((`8,${target.catTypeId}`).split(','))) : []
                console.log('catTypeId', catTypeId)
                Object.assign(form, {
                    ...target,
                    catTypeId,
                    status: (target.status !== '启用' && target.status !== '0') ? '1' : '0',
                })

                console.log('当前企业', target)
            })
            .catch(() => {
                console.log('取消')
            })
    }
}
</script>

<template>
    <ElCard class="mb-20">
        <ElRow>
            <ElButton @click="goToList">
                返回列表
            </ElButton>
        </ElRow>

        <div class="info-title">
            企业注册信息
        </div>

        <ElForm ref="formRef"
                :model="form"
                label-position="top"
                label-width="auto"
                :rules="rules"
        >
            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业号"
                                prop="enterpriseId"
                    >
                        <ElInput v-model="form.enterpriseId"
                                 :disabled="true"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业名称"
                                prop="enterpriseName"
                    >
                        <ElInput v-model="form.enterpriseName"
                                 :disabled="isEdit"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="统一社会信用代码"
                                prop="unifiedSocialCreditCode"
                    >
                        <ElInput v-model="form.unifiedSocialCreditCode"
                                 :disabled="isEdit"
                                 maxlength="18"
                                 @input="creditCodeChange"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业级别"
                                prop="enterpriseLevelId"
                    >
                        <ElRadioGroup v-model="form.enterpriseLevelId"
                                      @change="enterpriseLevelChange"
                        >
                            <ElRadio v-for="item in EnterpriseRank"
                                     :key="item.value"
                                     :value="item.value"
                            >
                                {{ item.label }}
                            </ElRadio>
                        </ElRadioGroup>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="业务类别"
                                prop="catTypeId"
                    >
                        <!-- :disabled="true" -->
                        <ElSelect v-model="form.catTypeId"
                                  collapse-tags
                                  collapse-tags-tooltip
                                  multiple
                        >
                            <ElOption v-for="item in CatType"
                                      :key="item.value"
                                      :value="item.value"
                                      :label="item.label"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="企业注册地址"
                        prop="registeredAddress"
            >
                <Address v-model="form.registeredAddress" />
            </ElFormItem>

            <ElFormItem label="企业状态"
                        prop="status"
            >
                <ElSwitch v-model="form.status"
                          active-value="0"
                          inactive-value="1"
                />
            </ElFormItem>

            <div class="info-title">
                企业管理员信息
            </div>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="企业管理员账号"
                                prop="enterpriseAccount"
                    >
                        <ElInput v-model="form.enterpriseAccount"
                                 :disabled="true"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="姓名"
                                prop="userName"
                    >
                        <ElInput v-model="form.userName" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="手机号"
                                prop="phonenumber"
                    >
                        <ElInput v-model="form.phonenumber"
                                 maxlength="11"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <div style="text-align: center;">
                <ElButton type="primary"
                          @click="doSave(formRef)"
                >
                    保存
                </ElButton>

                <ElButton @click="goToList">
                    取消
                </ElButton>
            </div>
        </ElForm>
    </ElCard>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
}

.tip_box {
    :deep(.el-form-item__content) {
        display: flex;
        flex-direction: row;
        align-items: flex-end;

        .tips {
            padding-left: 5px;
        }
    }
}
</style>
